<template>
  <el-card>
    <template #header>
      <div class="card-header">
        <span>
          <span>{{ columnMediaConfig.channelName }}</span>
          <span v-if="columnMediaConfig.columnName"> > </span>
          <span>{{ columnMediaConfig.columnName }}</span>
        </span>
        <!--        <span>符合条件的媒资{{tableData.total}}条</span>-->
      </div>
    </template>
    <el-row class="mb10">
      <el-col :span="12">
        <el-input placeholder="请输入媒资名称" v-model.trim="mediaQuery.keyword" size="mini" class="input-w mr10" clearable
          @clear="handleFilter" @keyup.enter="handleFilter" />
        <el-button type="primary" size="mini" @click="handleFilter">
          <el-icon>
            <search />
          </el-icon>
          搜索
        </el-button>
      </el-col>
      <el-col :span="12">
        <div align="right">
          <el-button type="primary" size="mini" @click="handleSelectMedia"
            :disabled="!columnMediaConfig.selectedColumn">
            <el-icon>
              <plus />
            </el-icon>
            从媒资包添加
          </el-button>
          <el-button type="danger" size="mini" @click="handleDeleteMedia" :disabled="!columnMediaConfig.selectedColumn">
            <el-icon>
              <delete />
            </el-icon>
            移除
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-table ref="columnMediaTableRef" :data="tableData.listData" v-loading="isloading" border @select-all="handleSelectAll" @select="handleSelect" @row-click="handleClickRow" style="overflow-y: auto;">
      <el-table-column type="selection" width="60" :selectable="handleSelectAble" />
      <el-table-column label="预览" width="60">
        <template #default="{ row }">
          <span @click.stop>
            <el-image v-if="typeof row.thumbs == 'object' && row.thumbs.length > 0"
              :src="row.thumbs[0].isself == 1 ? row.thumbs[0].viewurl + '&width=60px' : row.thumbs[0].viewurl"
              :preview-src-list="srcList" :initial-index="initialIndex(row.thumbs)" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="媒资名称" prop="name" show-overflow-tooltip />
      <el-table-column label="媒资类型" prop="mediatypename" />
      <!-- <el-table-column label="排序号(倒序)" width="60" prop="sort"></el-table-column>
      <el-table-column label="操作" prop="sort">
        <template #default="{ row }">
          <el-link type="primary" @click="sortHandleClick(row)">修改排序</el-link>
        </template>
      </el-table-column> -->
    </el-table>
    <el-row class="mt10">
      <el-col :span="24">
        <table-pagination :queryList="mediaQuery" :total="tableData.total"
          @pagination="columnMediaConfig.selectedColumn ? getColumnMediaList() : getChannelMediaList()" />
      </el-col>
    </el-row>
  </el-card>
  <el-dialog v-model="dialogSortFormVisible" :title="sortMedia.name" width="20%">
    <el-form :model="form">
      <el-form-item label="排序" :label-width="formLabelWidth">
        <el-input v-model="sortMedia.sort" autocomplete="off">
          <template #suffix>
            <div class="el-input-tip">倒序（越大越靠前）</div>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogSortFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogSortFormVisible = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  <package-media ref="packageMediaRef" :dialog-visible="dialogVisible" @handleCancelDialog="handleCancelDialog"
    :packageid="mediaQuery.packageid" :columnid="mediaQuery.columnid" @reloadColumnMedias="getColumnMediaList" />
</template>

<script>
import { reactive, toRef, ref, computed, nextTick, onMounted, onUnmounted } from 'vue'
import { getPackageChannelMedias, getPackageColumnMedias, deleteColumnRelMedia } from "@/api/package/package";
import { Search, Plus, Delete } from "@element-plus/icons"
import TablePagination from "@/views/public/TablePagination";
import PackageMedia from "./PackageMedia";
import { ElMessageBox, ElMessage } from 'element-plus'

export default {
  name: "ColumnMedia",
  components: { Search, Plus, Delete, TablePagination, PackageMedia },
  props: {
    packageid: {
      type: Number,
      required: true
    },
    mediaQueryList: {
      type: Object
    },
    columnMediaConfig: {
      type: Object
    }
  },
  setup(props) {
    const mediaQuery = toRef(props, 'mediaQueryList')
    const isloading = ref(false)
    const tableData = reactive({
      total: 0,
      listData: []
    })
    const srcList = ref([])
    const dialogVisible = ref(false)
    const packageMediaRef = ref(null)
    const columnMediaTableRef = ref(null)

    function setTableAutoHeight() {
      if (columnMediaTableRef.value) {
        // 获取 el-table 的 DOM 元素
        const tableElement = columnMediaTableRef.value.$el;

        const headerHeight = 360;
        const footerHeight = 10;

        const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

        const autoHeight = viewportHeight - headerHeight - footerHeight;

        tableElement.style.height = autoHeight + 'px';
      }
    }

    onMounted(() => {
      setTableAutoHeight()
      window.addEventListener('resize', setTableAutoHeight);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', setTableAutoHeight);
    });

    const formData = reactive({
      columnid: undefined,
      packageid: undefined,
      mediaids: []
    })
    const dialogSortFormVisible = ref(false)
    const sortMedia = reactive({
      'sort': 1,
      'name': '',
      'mediaid': null,
      'packageid': null,
    })

    const initialIndex = computed(() => {
      return (thumbs) => {
        const index = srcList.value.findIndex(d => d === thumbs[0].viewurl)
        return index
      }
    })

    /** 获取频道媒资列表 **/
    const getChannelMediaList = () => {
      isloading.value = true
      getPackageChannelMedias(mediaQuery.value).then(response => {
        isloading.value = false
        const { total, list } = response.data
        tableData.total = total
        tableData.listData = list
        srcList.value = []
        tableData.listData.forEach(row => {
          if (row.thumbs.length > 0) {
            srcList.value.push(row.thumbs[0].viewurl)
          }
        })
      })
    }
    /** 获取频道栏目媒资列表 **/
    const getColumnMediaList = () => {
      isloading.value = true
      formData.mediaids = []
      getPackageColumnMedias(mediaQuery.value).then(response => {
        isloading.value = false
        const { total, list } = response.data
        tableData.total = total
        tableData.listData = list
        srcList.value = []
        tableData.listData.forEach(row => {
          if (row.thumbs.length > 0) {
            srcList.value.push(row.thumbs[0].viewurl)
          }
        })
      })
    }

    // 点击排序链接时 触发
    const sortHandleClick = (row) => {
      sortMedia.name = row.name
      sortMedia.sort = row.sort

      dialogSortFormVisible.value = true;
    };

    /** 从媒包中添加媒资 **/
    const handleSelectMedia = () => {
      dialogVisible.value = true
      nextTick(() => {
        packageMediaRef.value.init()
      })
    }
    /** 关闭弹框 **/
    const handleCancelDialog = () => {
      dialogVisible.value = false
    }
    /** 搜索媒资 **/
    const handleFilter = () => {
      mediaQuery.value.page = 1
      if (props.columnMediaConfig.selectedColumn) {
        getColumnMediaList()
      } else {
        getChannelMediaList()
      }
    }
    /** 单个选择 **/
    const handleSelect = (selection, row) => {
      getSelectedMediaIds(row)
    }
    /** 全选 **/
    const handleSelectAll = (selection) => {
      if (selection.length > 0) {
        selection.forEach(row => {
          if (!formData.mediaids.includes(row.mediaid)) {
            formData.mediaids.push(row.mediaid)
          }
        })
      } else {
        formData.mediaids = []
      }
    }
    /** 点击行选择 **/
    const handleClickRow = (row) => {
      if (props.columnMediaConfig.selectedColumn) {
        getSelectedMediaIds(row)
      }
    }
    /** 选取要删除的媒资ID **/
    const getSelectedMediaIds = (row) => {
      if (formData.mediaids.includes(row.mediaid)) {
        const index = formData.mediaids.findIndex(d => d == row.mediaid)
        formData.mediaids.splice(index, 1)
        columnMediaTableRef.value.toggleRowSelection(row, false)
      } else {
        formData.mediaids.push(row.mediaid)
        columnMediaTableRef.value.toggleRowSelection(row, true)
      }
    }
    /** 删除栏目中的媒资 **/
    const handleDeleteMedia = () => {
      if (formData.mediaids.length <= 0) {
        ElMessage({ type: 'warning', message: '请选择要删除的媒资', duration: 2000 })
      } else {
        formData.columnid = mediaQuery.value.columnid
        formData.packageid = props.packageid
        ElMessageBox.confirm('已选择 ' + formData.mediaids.length + ' 条媒资，确定要删除吗？', '删除栏目 ' + props.columnMediaConfig.columnName + ' 中的媒资', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteColumnRelMedia(formData).then(response => {
            if (response.errcode == 0) {
              ElMessage({ type: 'success', message: response.msg, duration: 2000 })
              getColumnMediaList()
            }
          })
        }).catch(() => { })
      }
    }
    /** 判断媒资是否可选 **/
    const handleSelectAble = () => {
      return props.columnMediaConfig.selectedColumn
    }

    const init = () => {
      getChannelMediaList()
    }

    return {
      sortHandleClick,
      dialogSortFormVisible,
      sortMedia,
      mediaQuery,
      isloading,
      init,
      tableData,
      getChannelMediaList,
      getColumnMediaList,
      srcList,
      initialIndex,
      handleSelectMedia,
      dialogVisible,
      handleCancelDialog,
      packageMediaRef,
      handleFilter,
      handleSelect,
      handleSelectAll,
      handleClickRow,
      columnMediaTableRef,
      setTableAutoHeight,
      handleDeleteMedia,
      handleSelectAble
    }
  }
}
</script>

<style scoped>
.el-input-tip {
  color: #909399;
  /* 文本颜色 */
  font-size: 12px;
  /* 字体大小 */
  margin-left: 8px;
  /* 与输入框的间距 */
  display: inline-block;
  /* 行内块级元素 */
  vertical-align: middle;
  /* 垂直居中 */
}
</style>
